package com.supergdtop.www.run.tools;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;

/**
 * 权限检测工具
 * Created by Asum on 2016/6/24 0024.
 */
public class PermissionTools {
    public static final int PERMISSION_REQUEST_CODE = 1;

    public static boolean check(Activity activity) {
        int count = 0;
        ArrayList<String> ps = new ArrayList<>();

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            count++;
            ps.add(Manifest.permission.ACCESS_COARSE_LOCATION); //用于进行网络定位
        }

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            count++;
            ps.add(Manifest.permission.ACCESS_FINE_LOCATION); //用于访问GPS定位
        }

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            count++;
            ps.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);//写入扩展存储，向扩展卡写入数据，用于写入缓存定位数据
        }

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            count++;
            ps.add(Manifest.permission.READ_PHONE_STATE);//用于读取手机当前的状态
        }

        String[] permissions = new String[count];
        for (int i = 0; i < count; i++) {
            permissions[i] = ps.get(i);
        }

        if (permissions.length > 0) {
            ActivityCompat.requestPermissions(activity, permissions, PERMISSION_REQUEST_CODE);
            return false;
        } else {
            return true;
        }
    }

    public static boolean checkCallPhone(Activity activity) {
        ArrayList<String> ps = new ArrayList<>();

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ps.add(Manifest.permission.CALL_PHONE); //用于拨打电话
        }

        String[] permissions = new String[ps.size()];
        for (int i = 0; i < ps.size(); i++) {
            permissions[i] = ps.get(i);
        }

        if (permissions.length > 0) {
            ActivityCompat.requestPermissions(activity, permissions, PERMISSION_REQUEST_CODE);
            return false;
        } else {
            return true;
        }
    }
}
